package vn.lumi.smarthome.ui;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import net.margaritov.preference.colorpicker.ColorPickerDialog;
import net.margaritov.preference.colorpicker.ColorPickerDialog.OnColorChangedListener;
import net.margaritov.preference.colorpicker.ColorPickerDialog.OnTouchReleasedListener;
import net.margaritov.preference.colorpicker.ColorPickerPanelView;
import net.margaritov.preference.colorpicker.ColorPickerView;
import vn.lumi.smarthome.Config;
import vn.lumi.smarthome.LumiHome;
import vn.lumi.smarthome.R;
import vn.lumi.smarthome.io.database.DatabaseHelper;
import vn.lumi.smarthome.io.database.TBL_Device;
import vn.lumi.smarthome.io.database.TBL_DeviceState;
import vn.lumi.smarthome.io.database.TBL_Schedule;
import vn.lumi.smarthome.io.model.Device;
import vn.lumi.smarthome.io.model.DeviceState;
import vn.lumi.smarthome.io.model.Device.OnControlDeviceListener;
import vn.lumi.smarthome.service.VibrateThread;
import vn.lumi.smarthome.ui.EditScheduleActivity.DeleteScheduleReceiver;
import vn.lumi.smarthome.ui.LoginActivity.GetDataSocket;
import vn.lumi.smarthome.ulti.LogUltis;
import vn.lumi.smarthome.ulti.Preference;
import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class DeviceFragment extends BaseFragment implements
		LoaderCallbacks<Cursor>, OnControlDeviceListener {
	private static final String TAG = "DeviceFragment";

	private static DeviceFragment sDeviceFragment;

	// Khai bao cac tham so chua View
	private ListView mlistDevices;

	// Khai bao bien luu adapter cho listview
	private DeviceAdapter mDeviceAdapter;

	// Khai bao ID cua Loader
	private static final int LOADER_ID = 1;

	DeviceReceiver mReceiver;
	/**
	 * Bien nay dung de han che bat thiet bi qua nhanh, chi khi thiet bi bat or
	 * tat xong thi moi cho phep bat thiet bi khac
	 */
	private boolean isAllowTurnOn = true;

	// public static final int BLIND_LEFT1 = 0;
	// public static final int BLIND_STOP = 1;
	// public static final int BLIND_RIGHT = 2;
	private boolean isRestartLoadder = true;

	/**
	 * 
	 * @param floor_id
	 * @param room_id
	 * @return
	 */
	public static DeviceFragment newInstance(int floor_id, int room_id) {

		if (sDeviceFragment == null) {
			sDeviceFragment = new DeviceFragment();
		}
		Bundle bundle = new Bundle();
		bundle.putInt(FLOOR_ID, floor_id);
		bundle.putInt(ROOM_ID, room_id);
		sDeviceFragment.setArguments(bundle);
		return sDeviceFragment;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		isRestartLoadder = true;
		mFloor_id = getArguments().getInt(FLOOR_ID);
		mRoom_id = getArguments().getInt(ROOM_ID);

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.support.v4.app.Fragment#onResume()
	 */
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Config.isVibrate = Preference.getVibrate(getActivity());
		// Config.configLanguage(getActivity().getBaseContext(),
		// Preference.getLanguage(getActivity().getApplicationContext()));//
		// Thiet lap
		// // ngon ngu
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater
				.inflate(R.layout.fragment_device, container, false);
		init_view(view);
		refreshData(mFloor_id, mRoom_id);

		return view;
	}

	private void init_view(View view) {
		mlistDevices = (ListView) view.findViewById(R.id.fragment_device_list);

		mDeviceAdapter = new DeviceAdapter(getActivity(), null,
				CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);

		mDeviceAdapter.setOnControlDeviceListener(this);
		mlistDevices.setAdapter(mDeviceAdapter);

	}

	@Override
	public void refreshData(int floor_id, int room_id) {
		mFloor_id = floor_id;
		mRoom_id = room_id;
		Bundle bundle = new Bundle();
		bundle.putInt(FLOOR_ID, mFloor_id);
		bundle.putInt(ROOM_ID, mRoom_id);
		getLoaderManager().restartLoader(LOADER_ID, bundle, this);
	}

	public void turnAllOffOnRoom(int room_id) {
		ArrayList<Device> devicesOnOff = new ArrayList<Device>();
		ArrayList<Device> devicesRGB = new ArrayList<Device>();
		Cursor cursor = null;
		String selection = DatabaseHelper.DB_TBL_DEVICE + "."
				+ TBL_Device.ROOM_ID + "=?";
		String[] selectionArgs = new String[] { room_id + "" };
		cursor = getActivity().getContentResolver().query(
				TBL_Device.CONTENT_URI_DEVICES, null, selection, selectionArgs,
				null);
		cursor.moveToFirst();
		for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
			// do what you need with the cursor here

			switch (getItemViewType(cursor)) {
			case Device.TYPE_LAYOUT_RGB:

				break;

			case Device.TYPE_LAYOUT_ONOFF:
				Device deviceNormal = getDevice(cursor);
				if (deviceNormal.getDeviceState().getValue() == Device.DEVICE_STATE_DEVICE_ON) {
					devicesOnOff.add(deviceNormal);
				}
				break;
			case Device.TYPE_LAYOUT_DIMMER:
				Device deviceDim = getDevice(cursor);
				if (deviceDim.getDeviceState().getValue() > Device.DEVICE_STATE_DIMMER_OFF) {
					devicesOnOff.add(deviceDim);
				}
				break;
			}
		}
		cursor.close();
		cursor = null;
		int[] valueOnOff = new int[devicesOnOff.size()];
		if (devicesOnOff.size() != 0) {
			for (int i = 0; i < devicesOnOff.size(); i++) {
				valueOnOff[i] = Device.DEVICE_STATE_DEVICE_OFF;
			}

			onControlNormalDevice(convertArraylistDeviceToArray(devicesOnOff),
					valueOnOff);
		}

	}

	public void turnAllOnOnRoom(int room_id) {
		ArrayList<Device> devicesOnOff = new ArrayList<Device>();
		ArrayList<Device> devicesRGB = new ArrayList<Device>();

		Cursor cursor = null;
		String selection = DatabaseHelper.DB_TBL_DEVICE + "."
				+ TBL_Device.ROOM_ID + "=?";
		String[] selectionArgs = new String[] { room_id + "" };
		cursor = getActivity().getContentResolver().query(
				TBL_Device.CONTENT_URI_DEVICES, null, selection, selectionArgs,
				null);
		cursor.moveToFirst();
		for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
			// do what you need with the cursor here

			switch (getItemViewType(cursor)) {
			case Device.TYPE_LAYOUT_RGB:

				break;
			case Device.TYPE_LAYOUT_ONOFF:
				Device deviceOnOff = getDevice(cursor);
				if (deviceOnOff.getDeviceState().getValue() == Device.DEVICE_STATE_DEVICE_OFF) {
					devicesOnOff.add(deviceOnOff);
				}
				break;
			case Device.TYPE_LAYOUT_DIMMER:
				Device deviceDim = getDevice(cursor);
				if (deviceDim.getDeviceState().getValue() == Device.DEVICE_STATE_DIMMER_OFF) {
					devicesOnOff.add(deviceDim);
				}
				break;
			}

		}
		cursor.close();
		cursor = null;
		int[] valueOnOff = new int[devicesOnOff.size()];
		if (devicesOnOff.size() != 0) {
			for (int i = 0; i < devicesOnOff.size(); i++) {
				valueOnOff[i] = Device.DEVICE_STATE_DEVICE_ON;
			}

			onControlNormalDevice(convertArraylistDeviceToArray(devicesOnOff),
					valueOnOff);
		}

	}

	private Device[] convertArraylistDeviceToArray(ArrayList<Device> Devices) {
		Device[] devices = new Device[Devices.size()];
		for (int i = 0; i < Devices.size(); i++) {
			devices[i] = Devices.get(i);
		}
		return devices;
	}

	protected Device getDevice(Cursor cursor) {
		int device_id = cursor.getInt(cursor.getColumnIndex(TBL_Device._ID));
		int device_type = cursor.getInt(cursor
				.getColumnIndex(TBL_Device.TYPE_ID));
		int room_id = cursor.getInt(cursor.getColumnIndex(TBL_Device.ROOM_ID));
		String device_name = cursor.getString(cursor
				.getColumnIndex(TBL_Device.NAME));
		int device_stateid = cursor.getInt(cursor
				.getColumnIndex(TBL_Device.STATE_ID));
		boolean isControl = false;
		int control = cursor.getInt(cursor
				.getColumnIndex(TBL_Device.IS_CONTROL));
		if (control == 1)
			isControl = true;
		else
			isControl = false;
		// int

		int value = cursor.getInt(cursor.getColumnIndex(TBL_DeviceState.VALUE));
		int RGB = cursor.getInt(cursor.getColumnIndex(TBL_DeviceState.RGB));

		DeviceState deviceState = new DeviceState(device_stateid, value, RGB, 0);
		return new Device(device_id, device_type, room_id, device_name,
				device_stateid, deviceState, isControl);
	}

	protected int getItemViewType(Cursor cursor) {
		return Device.getLayoutType(cursor.getInt(cursor
				.getColumnIndex(TBL_Device.TYPE_ID)));
	}

	@Override
	public Loader<Cursor> onCreateLoader(int arg0, Bundle bundle) {
		String selection = DatabaseHelper.DB_TBL_DEVICE + "."
				+ TBL_Device.ROOM_ID + "=?";
		int room_id = bundle.getInt(ROOM_ID);

		String[] selectionArgs = new String[] { room_id + "" };
		return new CursorLoader(getActivity(), TBL_Device.CONTENT_URI_DEVICES,
				null, selection, selectionArgs, TBL_Device.NUM_ORDER + ","
						+ DatabaseHelper.DB_TBL_DEVICE + "." + TBL_Device._ID
						+ " " + "ASC");
	}

	@Override
	public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
		mDeviceAdapter.swapCursor(cursor);
	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
		mDeviceAdapter.swapCursor(null);
	}

	@Override
	public void onControlNormalDevice(Device[] device, int[] value) {
		if (isAllowTurnOn) {
			ContentValues values = new ContentValues();
			int[] deviceID = new int[device.length];
			int[] stateValue = new int[device.length];
			int[] stateID = new int[device.length];
			for (int i = 0; i < device.length; i++) {
				deviceID[i] = device[i].getId();
				stateValue[i] = value[i];
				stateID[i] = device[i].getState_id();
			}
			values.put("DeviceID", convertIntArrayToString(deviceID));
			values.put("DeviceStateValue", convertIntArrayToString(stateValue));
			values.put("StateID", convertIntArrayToString(stateID));
			getActivity().getContentResolver().update(
					TBL_Device.CONTENT_URI_CONTROL_NORMAL_DEVICE, values, null,
					null);
			isAllowTurnOn = false;
			// //set broadcast receiver
			mReceiver = new DeviceReceiver();
			IntentFilter filter = new IntentFilter();
			filter.addAction(getActivity().getString(
					R.string.txt_broadcast_device_control_successful));
			filter.addAction(getActivity().getString(
					R.string.txt_broadcast_device_control_failed));
			getActivity().registerReceiver(mReceiver, filter);
		}

	}

	@Override
	public void onControlRGB(Device[] device, int[] value) {
		// TODO Auto-generated method stub
		if (isAllowTurnOn) {
			ContentValues values = new ContentValues();
			int[] deviceID = new int[device.length];
			int[] stateValue = new int[device.length];
			int[] stateID = new int[device.length];
			for (int i = 0; i < device.length; i++) {
				deviceID[i] = device[i].getId();
				stateValue[i] = value[i];
				stateID[i] = device[i].getState_id();
			}
			values.put("DeviceID", convertIntArrayToString(deviceID));
			values.put("DeviceStateValue", convertIntArrayToString(stateValue));
			values.put("StateID", convertIntArrayToString(stateID));
			getActivity().getContentResolver().update(
					TBL_Device.CONTENT_URI_CONTROL_RGB, values, null, null);
			isAllowTurnOn = false;

			mReceiver = new DeviceReceiver();
			IntentFilter filter = new IntentFilter();
			filter.addAction(getActivity().getString(
					R.string.txt_broadcast_device_control_successful));
			filter.addAction(getActivity().getString(
					R.string.txt_broadcast_device_control_failed));
			getActivity().registerReceiver(mReceiver, filter);
		}
	}

	public static String convertIntArrayToString(int[] data) {
		String result = "";
		for (int i = 0; i < data.length; i++) {
			result += String.valueOf(data[i]) + ",";
		}
		return result;

	}

	public static int[] convertStringToIntArray(String str) {
		if (str == "")
			return null;
		String[] array = str.split(",");
		int[] result = new int[array.length];
		for (int i = 0; i < array.length; i++) {
			result[i] = Integer.parseInt(array[i]);
		}
		return result;
	}

	public class MyThread extends Thread {
		private Context context;
		private ContentValues mContentValues;
		private String mSelection;
		private String[] mSelectionArgs;
		private Device device;

		public MyThread(Context context, ContentValues contentValues,
				String selection, String[] selectionArgs, Device device) {
			this.context = context;
			mContentValues = contentValues;
			mSelection = selection;
			mSelectionArgs = selectionArgs;
			this.device = device;
		}

		@Override
		public void run() {
			super.run();
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			ContentValues values = new ContentValues();
			values.put(TBL_Device.IS_CONTROL, 0);

			String s1 = TBL_Device._ID + "=?";
			String[] s2 = new String[] { device.getId() + "" };

			int e = context.getContentResolver().update(
					TBL_Device.CONTENT_URI_DEVICES, values, s1, s2);
			int effect = context.getContentResolver().update(
					TBL_DeviceState.CONTENT_URI_DEVICE_STATE, mContentValues,
					mSelection, mSelectionArgs);
			LogUltis.e(TAG, "Effect=" + effect);

		}
	}

	private class DeviceAdapter extends MyCursorAdapter {
		private static final String TAG = "DeviceAdapter";

		private OnControlDeviceListener mOnControlDeviceListener;
		private ColorPickerDialog mColorPickerDialog;
		private ColorPickerView mColorPickerView;
		int colorPicker;
		Context mContext = null;

		public DeviceAdapter(Context context, Cursor c, int flags) {
			super(context, c, flags);
			this.mContext = context;
		}

		public void setOnControlDeviceListener(
				OnControlDeviceListener controlDeviceListener) {
			mOnControlDeviceListener = controlDeviceListener;
		}

		@Override
		public boolean isEnabled(int position) {
			return false;
		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup arg2) {
			int layout_type = getItemViewType(cursor);
			// int layout_type=Device.getLayoutType(device_type);
			View view = null;

			switch (layout_type) {
			case Device.TYPE_LAYOUT_ONOFF:
				view = View.inflate(context,
						R.layout.item_listview_device_onoff, null);
				break;
			case Device.TYPE_LAYOUT_RGB:
				view = View.inflate(context, R.layout.item_list_device_rgb,
						null);
				break;
			case Device.TYPE_LAYOUT_DIMMER:
				view = View.inflate(context, R.layout.item_list_device_dimmer,
						null);
				break;

			case Device.TYPE_LAYOUT_VER_BLIND:
				view = View.inflate(context, R.layout.item_list_device_blind,
						null);
				break;
			case Device.TYPE_LAYOUT_HOR_BLIND:
				view = View.inflate(context, R.layout.item_list_device_blind,
						null);
				break;
			default:

				break;
			}
			return view;
		}

		@Override
		public void bindView(View view, final Context context, Cursor cursor) {
			int layout_type = getItemViewType(cursor);
			final int device_type = cursor.getInt(cursor
					.getColumnIndex(TBL_Device.TYPE_ID));
			final Device device = getDevice(cursor);

			// device schedule
			ImageView imgSchedule = new ImageView(context);
			final OnClickListener mOnScheduleClickListener = new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (Config.isVibrate)
						new VibrateThread(getActivity().getApplicationContext())
								.start();
					Intent i = new Intent(context, ScheduleListActivity.class);
					i.putExtra(ScheduleListActivity.EXTRA_DEVICE_ID,
							device.getId());
					i.putExtra(ScheduleListActivity.EXTRA_DEVICE_NAME,
							device.getName());
					i.putExtra(ScheduleListActivity.EXTRA_DEVICE_TYPE,
							device.getType_id());
					i.putExtra(ScheduleListActivity.EXTRA_ROOM_ID, mRoom_id);
					// context.startActivity(i);
					((Activity) context).startActivityForResult(i,
							MainActivity.ANOTHER_REQUEST);

				}

			};

			switch (layout_type) {
			case Device.TYPE_LAYOUT_ONOFF:
				// set name
				final TextView device_name = (TextView) view
						.findViewById(R.id.item_listview_device_onoff_txt_name);
				device_name.setText(device.getName());

				// set image
				final ImageView device_image = (ImageView) view
						.findViewById(R.id.item_listview_device_onoff_img_onoff);

				final int value = device.getDeviceState().getValue();
				Log.e("ban tin", "value: " + value);
				if (device.isControl()) {
					// device_image.setImageResource(R.drawable.ic_launcher);
				} else {
					if (device.getDeviceState().getValue() == Device.DEVICE_STATE_DEVICE_OFF) {
						if (device.getType_id() == Device.DEVICE_TYPE_LIGHT) {
							device_image
									.setImageResource(R.drawable.img_light_off_selector);
							device_name
									.setBackgroundResource(R.drawable.img_bg_dev_normal_name_off);
						} else if (device.getType_id() == Device.DEVICE_TYPE_AIRCON) {
							device_image
									.setImageResource(R.drawable.img_aircon_off_selector);
							device_name
									.setBackgroundResource(R.drawable.img_bg_dev_normal_name_off);

						} else if (device.getType_id() == Device.DEVICE_TYPE_HEATER)
							device_image
									.setImageResource(R.drawable.img_heater_off_selector);
						device_name
								.setBackgroundResource(R.drawable.img_bg_dev_normal_name_off);
					} else if (device.getDeviceState().getValue() == Device.DEVICE_STATE_DEVICE_ON) {
						if (device.getType_id() == Device.DEVICE_TYPE_LIGHT) {
							device_image
									.setImageResource(R.drawable.img_light_on_selector);
							device_name
									.setBackgroundResource(R.drawable.img_bg_dev_normal_name_on);
						} else if (device.getType_id() == Device.DEVICE_TYPE_AIRCON) {
							device_image
									.setImageResource(R.drawable.img_aircon_on_selector);
							device_name
									.setBackgroundResource(R.drawable.img_bg_dev_normal_name_on);
						} else if (device.getType_id() == Device.DEVICE_TYPE_HEATER) {
							device_image
									.setImageResource(R.drawable.img_heater_on_selector);
							device_name
									.setBackgroundResource(R.drawable.img_bg_dev_normal_name_on);
						}
					}
				}

				// image onclick
				device_image.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						if (device.isControl())
							return;
						if (device.getDeviceState().getValue() == Device.DEVICE_STATE_DEVICE_ON) {
							Device[] dev = new Device[] { device };
							int[] state = new int[] { Device.DEVICE_STATE_DEVICE_OFF };
							mOnControlDeviceListener.onControlNormalDevice(dev,
									state);
							if (Config.isVibrate)
								new VibrateThread(getActivity()
										.getApplicationContext()).start();
							// device_name.setBackgroundResource(R.drawable.img_bg_dev_normal_name_off);
							Log.e("ban tin", "Device state device on");
						} else if (device.getDeviceState().getValue() == Device.DEVICE_STATE_DEVICE_OFF) {
							Device[] dev = new Device[] { device };
							int[] state = new int[] { Device.DEVICE_STATE_DEVICE_ON };
							mOnControlDeviceListener.onControlNormalDevice(dev,
									state);
							if (Config.isVibrate)
								new VibrateThread(getActivity()
										.getApplicationContext()).start();
							// device_name.setBackgroundResource(R.drawable.img_bg_dev_normal_name_on);
							Log.e("ban tin", "Device state device off");
						}
					}
				});

				// schedule
				imgSchedule = (ImageView) view
						.findViewById(R.id.item_listview_device_onoff_img_schedule);
				imgSchedule.setOnClickListener(mOnScheduleClickListener);
				// Kiem tra xem co lich hay khong
				if (cursor.getInt(cursor.getColumnIndex("max_schedule_state")) != 2) // cot
																						// max_chedule_state
																						// la
																						// do
																						// dat
																						// ten
																						// tu
																						// cot
																						// MAX(SChedule_state)
					imgSchedule.setImageResource(R.drawable.img_schedule_off);
				else
					imgSchedule.setImageResource(R.drawable.img_schedule_on);
				Log.e("num", "num colum: " + cursor.getColumnCount()
						+ " num row:" + cursor.getCount());

				break;
			case Device.TYPE_LAYOUT_DIMMER:
				// set name
				TextView dimmer_name = (TextView) view
						.findViewById(R.id.item_listview_device_dimmer_txt_name);
				dimmer_name.setText(device.getName());

				// progress bar
				SeekBar seekBar = (SeekBar) view
						.findViewById(R.id.item_listview_device_valuechange_seekbar_change);
				if (device.getType_id() == Device.DEVICE_TYPE_DIMMER)
					seekBar.setMax(Device.DEVICE_STATE_DIMMER_MAX_LEVEL - 1);
				else if (device.getType_id() == Device.DEVICE_TYPE_FAN)
					seekBar.setMax(Device.DEVICE_STATE_FAN_MAX_LEVEL - 1);
				seekBar.setProgress(device.getDeviceState().getValue() - 1);
				seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

					@Override
					public void onProgressChanged(SeekBar arg0, int progress,
							boolean fromUser) {
					}

					@Override
					public void onStartTrackingTouch(SeekBar arg0) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onStopTrackingTouch(SeekBar seekBar) {
						// TODO Auto-generated method stub
						Device[] dev = new Device[] { device };
						int[] value = new int[] { seekBar.getProgress() + 1 };
						mOnControlDeviceListener.onControlNormalDevice(dev,
								value);

					}

				});

				// dimmer image
				final int dimmer_value = device.getDeviceState().getValue();
				final ImageView dimmer_image = (ImageView) view
						.findViewById(R.id.item_listview_device_dimmer_img_onoff);
				if (device.isControl()) {
					// dimmer_image.setPressed(true);
					// dimmer_image.setImageResource(R.drawable.ic_launcher);
				} else {
					// dimmer_image.setPressed(false);
					switch (device_type) {
					case Device.DEVICE_TYPE_DIMMER:
						if (dimmer_value == Device.DEVICE_STATE_DIMMER_OFF) {
							dimmer_image
									.setImageResource(R.drawable.img_light_off_selector);
						} else
							dimmer_image
									.setImageResource(R.drawable.img_light_on_selector);
						break;
					case Device.DEVICE_TYPE_FAN:
						if (dimmer_value == Device.DEVICE_STATE_FAN_OFF)
							dimmer_image
									.setImageResource(R.drawable.img_fan_off_selector);
						else
							dimmer_image
									.setImageResource(R.drawable.img_fan_on_selector);
						break;
					default:
						break;
					}
				}

				// on click
				dimmer_image.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						if (device.isControl())
							return;
						if (Config.isVibrate)
							new VibrateThread(getActivity()
									.getApplicationContext()).start();
						switch (device_type) {
						case Device.DEVICE_TYPE_DIMMER:
							if (dimmer_value == Device.DEVICE_STATE_DIMMER_OFF) {
								Device[] dev = new Device[] { device };
								int[] state = new int[] { Device.DEVICE_STATE_DIMMER_ON };
								mOnControlDeviceListener.onControlNormalDevice(
										dev, state);
							} else {
								Device[] dev = new Device[] { device };
								int[] state = new int[] { Device.DEVICE_STATE_DIMMER_OFF };
								mOnControlDeviceListener.onControlNormalDevice(
										dev, state);
							}
							break;
						case Device.DEVICE_TYPE_FAN:
							if (dimmer_value == Device.DEVICE_STATE_FAN_OFF) {
								Device[] dev = new Device[] { device };
								int[] state = new int[] { Device.DEVICE_STATE_FAN_ON };
								mOnControlDeviceListener.onControlNormalDevice(
										dev, state);
							} else {
								Device[] dev = new Device[] { device };
								int[] state = new int[] { Device.DEVICE_STATE_FAN_OFF };
								mOnControlDeviceListener.onControlNormalDevice(
										dev, state);
							}
							break;
						default:
							break;
						}
					}
				});

				// schedule
				imgSchedule = (ImageView) view
						.findViewById(R.id.item_listview_device_dimmer_img_schedule);
				imgSchedule.setOnClickListener(mOnScheduleClickListener);
				// Kiem tra xem co lich hay khong
				if (cursor.getInt(cursor.getColumnIndex("max_schedule_state")) != 2)
					imgSchedule.setImageResource(R.drawable.img_schedule_off);
				else
					imgSchedule.setImageResource(R.drawable.img_schedule_on);
				break;

			case Device.TYPE_LAYOUT_RGB:
				// set name
				final TextView rgb_name = (TextView) view
						.findViewById(R.id.item_list_device_rgb_txt_name);
				rgb_name.setText(device.getName());

				// color picker
				final int color = device.getDeviceState().getRGB() + 0xFF000000;
				final ColorPickerPanelView colorPickerPanelView = (ColorPickerPanelView) view
						.findViewById(R.id.item_list_device_rgb_color_panel);
				colorPickerPanelView.setColor(color);
				final OnColorChangedListener onColorChangedListener = new OnColorChangedListener() {
					@Override
					public void onColorChanged(int color) {
					}

					@Override
					public void onCancelDialog() {
						// TODO Auto-generated method stub
						// Device[] dev = new Device[]{device};
						// mOnControlRGBListener.onEndControlRGB(dev);
						// notifyDataSetChanged();
					}
				};
				final OnTouchReleasedListener onTouchReleasedListener = new OnTouchReleasedListener() {
					@Override
					public void onTouchReleased(int color) {
						colorPickerPanelView.setColor(color);

						// dieu khien RGB hoac truyen dieu khien RGB ra
						// interface o day
						color = Math.abs(color - 0xFF000000);
						Device[] dev = new Device[] { device };
						int Blue = color % 256;
						if (Blue < Math.abs(0xFF))
							Blue++;
						color = color / 256;
						int Green = color % 256;
						if (Green < Math.abs(0xFF))
							Green++;
						color = color / 256;
						int Red = color % 256;
						if (Red < Math.abs(0xFF))
							Red++;
						color = Blue + 256 * Green + 256 * 256 * Red;
						int[] state = new int[] { color };
						Log.d("RGB", "color, r, g, b = " + color + ", " + Red
								+ ", " + Green + ", " + Blue);
						mOnControlDeviceListener.onControlRGB(dev, state);

						notifyDataSetChanged();
					}
				};

				colorPickerPanelView.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
					}
				});

				// image view
				final ImageView rgb_image = (ImageView) view
						.findViewById(R.id.item_list_device_rgb_img_onoff);
				final int rgb_value = device.getDeviceState().getRGB();
				if (device.isControl()) {
					// rgb_image.setPressed(true);
				} else {
					// rgb_image.setPressed(false);
					if (java.lang.Math.abs(rgb_value) <= Device.DEVICE_STATE_RGB_OFF) {
						rgb_name.setBackgroundResource(R.drawable.img_bg_rgb_name_off);
					} else {
						rgb_image
								.setImageResource(R.drawable.img_rgb_on_selector);
						rgb_name.setBackgroundResource(R.drawable.img_bg_rgb_name_on);

					}

					rgb_image.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View arg0) {
							int color = colorPickerPanelView.getColor();
							showColorPickerDialog(onColorChangedListener,
									onTouchReleasedListener, color);

						}
					});
					rgb_name.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							if (Config.isVibrate)
								new VibrateThread(getActivity()
										.getApplicationContext()).start();
							if (device.isControl())
								return;
							if (java.lang.Math.abs(rgb_value) <= Device.DEVICE_STATE_RGB_OFF) {
								Device[] dev = new Device[] { device };
								int[] state = new int[] { colorPicker };
								mOnControlDeviceListener.onControlRGB(dev,
										state);
								// rgb_name.setBackgroundResource(R.drawable.img_bg_rgb_name_on);
							} else {
								Device[] dev = new Device[] { device };
								int[] state = new int[] { Device.DEVICE_STATE_RGB_OFF };
								mOnControlDeviceListener.onControlRGB(dev,
										state);
								// rgb_name.setBackgroundResource(R.drawable.img_bg_rgb_name_off);
								setColorPicker(color);
							}
						}
					});
				}

				// schedule
				imgSchedule = (ImageView) view
						.findViewById(R.id.item_list_device_rgb_img_schedule);
				imgSchedule.setOnClickListener(mOnScheduleClickListener);
				// Kiem tra xem co lich hay khong
				if (cursor.getInt(cursor.getColumnIndex("max_schedule_state")) != 2)
					imgSchedule.setImageResource(R.drawable.img_schedule_off);
				else
					imgSchedule.setImageResource(R.drawable.img_schedule_on);
				break;
			case Device.TYPE_LAYOUT_VER_BLIND:
				// set name
				TextView blind_name = (TextView) view
						.findViewById(R.id.item_list_device_blind_txt_name);
				if (blind_name != null)
					blind_name.setText(device.getName());

				// set image
				final ImageView blind_image = (ImageView) view
						.findViewById(R.id.item_list_device_blind_img_onoff);
				final int blind_position = device.getDeviceState().getValue();
				switch (blind_position) {
				case 1:
					blind_image.setImageResource(R.drawable.img_ver_blind_1);
					break;
				case 2:
					blind_image.setImageResource(R.drawable.img_ver_blind_2);
					break;
				case 3:
					blind_image.setImageResource(R.drawable.img_ver_blind_3);
					break;
				case 4:
					blind_image.setImageResource(R.drawable.img_ver_blind_4);
					break;
				case 5:
					blind_image.setImageResource(R.drawable.img_ver_blind_5);
					break;
				case 6:
					blind_image.setImageResource(R.drawable.img_ver_blind_6);
					break;
				case 7:
					blind_image.setImageResource(R.drawable.img_ver_blind_7);
					break;
				case 8:
					blind_image.setImageResource(R.drawable.img_ver_blind_8);
					break;

				}

				// control buttons
				ImageView blind_left = (ImageView) view
						.findViewById(R.id.item_list_device_blind_left); // left
																			// =
																			// open
				blind_left
						.setImageResource(R.drawable.img_ver_blind_open_selector);
				blind_left.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						Device[] dev = new Device[] { device };
						int[] state = new int[] { Device.DEVICE_STATE_BLIND_CMD__LEFT };
						mOnControlDeviceListener.onControlNormalDevice(dev,
								state);
						if (Config.isVibrate)
							new VibrateThread(getActivity()
									.getApplicationContext()).start();
					}
				});
				ImageView blind_stop = (ImageView) view
						.findViewById(R.id.item_list_device_blind_stop);
				blind_stop
						.setImageResource(R.drawable.img_hor_blind_stop_selector);
				blind_stop.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						Device[] dev = new Device[] { device };
						int[] state = new int[] { Device.DEVICE_STATE_BLIND_CMD_STOP };
						mOnControlDeviceListener.onControlNormalDevice(dev,
								state);
						if (Config.isVibrate)
							new VibrateThread(getActivity()
									.getApplicationContext()).start();
					}
				});
				ImageView blind_right = (ImageView) view
						.findViewById(R.id.item_list_device_blind_right);// right
																			// =
																			// close
				blind_right
						.setImageResource(R.drawable.img_ver_blind_close_selector);
				blind_right.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						Device[] dev = new Device[] { device };
						int[] state = new int[] { Device.DEVICE_STATE_BLIND_CMD_RIGHT };
						mOnControlDeviceListener.onControlNormalDevice(dev,
								state);
						if (Config.isVibrate)
							new VibrateThread(getActivity()
									.getApplicationContext()).start();
					}
				});

				// schedule
				imgSchedule = (ImageView) view
						.findViewById(R.id.item_list_device_blind_img_schedule);
				imgSchedule.setOnClickListener(mOnScheduleClickListener);
				// Kiem tra xem co lich hay khong
				if (cursor.getInt(cursor.getColumnIndex("max_schedule_state")) != 2)
					imgSchedule.setImageResource(R.drawable.img_schedule_off);
				else
					imgSchedule.setImageResource(R.drawable.img_schedule_on);
				break;
			case Device.TYPE_LAYOUT_HOR_BLIND:
				// set name
				TextView Hor_blind_name = (TextView) view
						.findViewById(R.id.item_list_device_blind_txt_name);
				if (Hor_blind_name != null)
					Hor_blind_name.setText(device.getName());

				// set image
				final ImageView Hor_blind_image = (ImageView) view
						.findViewById(R.id.item_list_device_blind_img_onoff);
				final int Hor_blind_position = device.getDeviceState()
						.getValue();
				switch (Hor_blind_position) {
				case 1:
					Hor_blind_image
							.setImageResource(R.drawable.img_hor_blind_1);
					break;
				case 2:
					Hor_blind_image
							.setImageResource(R.drawable.img_hor_blind_2);
					break;
				case 3:
					Hor_blind_image
							.setImageResource(R.drawable.img_hor_blind_3);
					break;
				case 4:
					Hor_blind_image
							.setImageResource(R.drawable.img_hor_blind_4);
					break;
				case 5:
					Hor_blind_image
							.setImageResource(R.drawable.img_hor_blind_5);
					break;
				case 6:
					Hor_blind_image
							.setImageResource(R.drawable.img_hor_blind_6);
					break;
				case 7:
					Hor_blind_image
							.setImageResource(R.drawable.img_hor_blind_7);
					break;
				case 8:
					Hor_blind_image
							.setImageResource(R.drawable.img_hor_blind_8);
					break;

				}

				// control buttons
				ImageView Hor_blind_left = (ImageView) view
						.findViewById(R.id.item_list_device_blind_left);
				Hor_blind_left
						.setImageResource(R.drawable.img_hor_blind_open_selector);
				Hor_blind_left.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						Device[] dev = new Device[] { device };
						int[] state = new int[] { Device.DEVICE_STATE_BLIND_CMD__LEFT };
						mOnControlDeviceListener.onControlNormalDevice(dev,
								state);
						if (Config.isVibrate)
							new VibrateThread(getActivity()
									.getApplicationContext()).start();
					}
				});
				ImageView Hor_blind_stop = (ImageView) view
						.findViewById(R.id.item_list_device_blind_stop);
				Hor_blind_stop
						.setImageResource(R.drawable.img_hor_blind_stop_selector);
				Hor_blind_stop.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						Device[] dev = new Device[] { device };
						int[] state = new int[] { Device.DEVICE_STATE_BLIND_CMD_STOP };
						mOnControlDeviceListener.onControlNormalDevice(dev,
								state);
						if (Config.isVibrate)
							new VibrateThread(getActivity()
									.getApplicationContext()).start();
					}
				});
				ImageView Hor_blind_right = (ImageView) view
						.findViewById(R.id.item_list_device_blind_right);
				Hor_blind_right
						.setImageResource(R.drawable.img_hor_blind_close_selector);
				Hor_blind_right.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						Device[] dev = new Device[] { device };
						int[] state = new int[] { Device.DEVICE_STATE_BLIND_CMD_RIGHT };
						mOnControlDeviceListener.onControlNormalDevice(dev,
								state);
						if (Config.isVibrate)
							new VibrateThread(getActivity()
									.getApplicationContext()).start();
					}
				});

				// schedule
				imgSchedule = (ImageView) view
						.findViewById(R.id.item_list_device_blind_img_schedule);
				imgSchedule.setOnClickListener(mOnScheduleClickListener);
				// Kiem tra xem co lich hay khong
				if (cursor.getInt(cursor.getColumnIndex("max_schedule_state")) != 2)
					imgSchedule.setImageResource(R.drawable.img_schedule_off);
				else
					imgSchedule.setImageResource(R.drawable.img_schedule_on);
				break;
			default:

				break;
			}
		}

		protected void showColorPickerDialog(
				OnColorChangedListener onColorChangedListener,
				OnTouchReleasedListener onTouchReleasedListener, int value) {
			mColorPickerDialog = new ColorPickerDialog(mContext, value);
			mColorPickerView = (ColorPickerView) mColorPickerDialog
					.findViewById(R.id.color_picker_view);
			mColorPickerView.setOnColorChangedListener(mColorPickerDialog);
			mColorPickerDialog
					.setOnColorChangedListener(onColorChangedListener);
			mColorPickerDialog
					.setOnTouchReleasedListener(onTouchReleasedListener);
			mColorPickerDialog.setCancelable(false);
			mColorPickerDialog.show();
		}

		private void setColorPicker(int color) {
			colorPicker = color;
		}
	}

	public class DeviceReceiver extends BroadcastReceiver {

		// private ProgressDialog mDialog;

		public DeviceReceiver() {
			// mDialog = dialog;
		}

		@Override
		public void onReceive(Context context, Intent intent) {
			// mDialog.cancel();
			getActivity().unregisterReceiver(mReceiver);
			if (intent
					.getAction()
					.equals(context
							.getString(R.string.txt_broadcast_device_control_successful))) {
				isAllowTurnOn = true;
				if (isRestartLoadder) {
					refreshData(mFloor_id, mRoom_id);

					isRestartLoadder = false;
				}

			}

			else if (intent
					.getAction()
					.equals(context
							.getString(R.string.txt_broadcast_device_control_failed))) {
				isAllowTurnOn = true;
				Log.e("ban tin", " Device faile");
				showCustomDialog(R.string.txt_error,
						R.string.txt_error_cannot_connect_HC);
			}
		}

	}

	public void showCustomDialog(int title, int message) {
		AlertDialog.Builder ErrorDialog = new AlertDialog.Builder(
				new ContextThemeWrapper(getActivity(),
						R.style.AlertDialogCustom));

		ChangeFont changeFont = new ChangeFont(getActivity());
		TextView tvTitle = new TextView(getActivity());
		tvTitle = changeFont.changeFontTextView(tvTitle, title,
				LumiHome.fontBold, LumiHome.sizeTittle, Gravity.CENTER,
				getResources().getColor(R.color.green));
		ErrorDialog.setCustomTitle(tvTitle);
		ErrorDialog.setMessage(message);
		ErrorDialog.setNegativeButton(R.string.glb_txt_return,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				});
		AlertDialog alertErrorDialog = ErrorDialog.create();
		alertErrorDialog.show();
		alertErrorDialog.getWindow().getAttributes();
		TextView tvMessage = (TextView) alertErrorDialog
				.findViewById(android.R.id.message);
		tvMessage = changeFont.changeFontTextView(tvMessage, message,
				LumiHome.font, LumiHome.sizeContent, Gravity.NO_GRAVITY,
				getResources().getColor(R.color.greenLight));

		Button btn1 = alertErrorDialog
				.getButton(DialogInterface.BUTTON_NEGATIVE);
		btn1.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),
				LumiHome.fontBold));
		btn1.setTextColor(getResources().getColor(R.color.greenActionbar));
		btn1.setTextSize(LumiHome.sizeButton);
	}

}
